<%@ page contentType="text/html;charset=UTF-8" %>
<script>
$(document).ready(function() {
	$('#productTable').bootstrapTable({
		 
		  //请求方法
               method: 'post',
               //类型json
               dataType: "json",
               contentType: "application/x-www-form-urlencoded",
               //显示检索按钮
               showSearch: true,
               //显示刷新按钮
               showRefresh: true,
               //显示切换手机试图按钮
               showToggle: true,
               //显示 内容列下拉框
    	       showColumns: true,
    	       //显示到处按钮
    	       showExport: true,
    	       //显示切换分页按钮
    	       showPaginationSwitch: true,
    	       //显示详情按钮
    	       /*detailView: true,
    	       	//显示详细内容函数
	           detailFormatter: "detailFormatter",*/
    	       //最低显示2行
    	       minimumCountColumns: 2,
               //是否显示行间隔色
               striped: true,
               //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）     
               cache: false,    
               //是否显示分页（*）  
               pagination: true,   
                //排序方式 
               sortOrder: "asc",  
               //初始化加载第一页，默认第一页
               pageNumber:1,   
               //每页的记录行数（*）   
               pageSize: 10,  
               //可供选择的每页的行数（*）    
               pageList: [10, 25, 50, 100, 500, 1000],
               //这个接口需要处理bootstrap table传递的固定参数,并返回特定格式的json数据  
               url: "${ctx}/product/product/data",
               //默认值为 'limit',传给服务端的参数为：limit, offset, search, sort, order Else
               //queryParamsType:'',   
               ////查询参数,每次调用是会带上这个参数，可自定义                         
               queryParams : function(params) {
               	var searchParam = $("#searchForm").serializeJSON();
               	searchParam.pageNo = params.limit === undefined? "1" :params.offset/params.limit+1;
               	searchParam.pageSize = params.limit === undefined? -1 : params.limit;
               	searchParam.orderBy = params.sort === undefined? "" : params.sort+ " "+  params.order;
                   return searchParam;
               },
               //分页方式：client客户端分页，server服务端分页（*）
               sidePagination: "server",
               contextMenuTrigger:"right",//pc端 按右键弹出菜单
               contextMenuTriggerMobile:"press",//手机端 弹出菜单，click：单击， press：长按。
               contextMenu: '#context-menu',
               onContextMenuItem: function(row, $el){
                   if($el.data("item") == "edit"){
                   		edit(row.id,row.state);
                   }else if($el.data("item") == "view"){
                       view(row.id);
                   } else if($el.data("item") == "delete"){
                        jp.confirm('确认要删除该云店商品记录吗？', function(){
                       	jp.loading();
                       	jp.get("${ctx}/product/product/delete?id="+row.id, function(data){
                   	  		if(data.success){
                   	  			$('#productTable').bootstrapTable('refresh');
                   	  			jp.success(data.msg);
                   	  		}else{
                   	  			jp.error(data.msg);
                   	  		}
                   	  	})
                   	   
                   	});
                      
                   } 
               },
              
               onClickRow: function(row, $el){
               },
               	onShowSearch: function () {
			$("#search-collapse").slideToggle();
		},
               columns: [
                 /*{
  		    	field: 'operate',
                title: '规格',
                align: 'center',
                events: {
                 	'click #skuManager': function (e, value, row, index) {
	   					$("#left").attr("class", "col-sm-6");
	   					setTimeout(function(){
	   						$("#right").fadeIn(500);
	   					},500);
	   					$("#productName").html(row.title);
	   					$("#productId").val(row.id);
	   					if(row.state=='0'){
	   						$("#subsectionButton").attr("disabled","disabled");
	   					}else{
	   						$("#subsectionButton").removeAttr("disabled");
	   					}
	   					//$('#productSkuTable').bootstrapTable("refresh",{query:{productId:row.id}})
	   					$('#productSkuTable').bootstrapTable("refresh")
                 	 }
                  },
                  formatter:  function operateFormatter(value, row, index) {
                	  return '<a href="#" id="skuManager" class="glyphicon glyphicon-th shouquan" title="规格管理"></a>';
                  }
  		    }
           	,*/{
		        checkbox: true
		    }
           	<c:if test="${fns:getUser().isShop() == false}">
           	,{
		        field: 'store.title',
		        title: '店铺',
		        sortable: true,
		        sortName: 'store.title'
		       
		    }
           	</c:if>
			,{
		        field: 'title',
		        title: '商品名称',
		        sortable: true,
		        sortName: 'title'
	        	,formatter:function(value, row , index){

	 			   if(value == null || value ==""){
	 				   value = "-";
	 			   }
	 			   <c:choose>
	 			      <c:when test="${fns:hasPermission('product:product:edit')}">
	 			      	return "<a href='javascript:edit(\""+row.id+"\",\""+row.state+"\")'>"+value+"</a>";
	 			      </c:when>
	 				  <c:when test="${fns:hasPermission('product:product:view')}">
	 				      return "<a href='javascript:view(\""+row.id+"\")'>"+value+"</a>";
	 			      </c:when>
	 				  <c:otherwise>
	 				      return value;
	 			      </c:otherwise>
	 			   </c:choose>

	 		        }
		    }
			/*,{
		        field: 'subtitle',
		        title: '副标题',
		        sortable: true,
		        sortName: 'subtitle'
		       
		    }*/
			,{
		        field: 'brand.title',
		        title: '品牌',
		        sortable: true,
		        sortName: 'brand.title'
		       
		    }
		    ,{
		        field: 'icon',
		        title: '列表图',
		        sortable: true,
		        sortName: 'icon',
		        formatter:function(value, row , index){
		        	if(value != null && value != ''){
		        		return '<img   onclick="jp.showPic(\''+value+'\')"'+' height="50px" src="'+value+'">';
		        	}
		        	return "";
		        }
		       
		    }
		   /* ,{
		        field: 'images',
		        title: '轮播图',
		        sortable: true,
		        sortName: 'images',
		        formatter:function(value, row , index){
		        	var labelArray = [];
		        	if(value != null && value != ''){
		        		var valueArray = value.split("|");
		        		for(var i =0 ; i<valueArray.length; i++){
		        			if(!/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(valueArray[i]))
		        			{
		        				labelArray[i] = "<a href=\""+valueArray[i]+"\" url=\""+valueArray[i]+"\" target=\"_blank\">"+decodeURIComponent(valueArray[i].substring(valueArray[i].lastIndexOf("/")+1))+"</a>"
		        			}else{
		        				labelArray[i] = '<img   onclick="jp.showPic(\''+valueArray[i]+'\')"'+' height="50px" src="'+valueArray[i]+'">';
		        			}
		        		}
		        	}
		        	return labelArray.join(" ");
		        }
		       
		    }*/
			,{
		        field: 'category.name',
		        title: '分类',
		        sortable: true,
		        sortName: 'category.name'
		       
		    }
			,{
		        field: 'sales',
		        title: '销量',
		        sortable: true,
		        sortName: 'sales'
		       
		    }
			/*,{
		        field: 'hits',
		        title: '浏览量',
		        sortable: true,
		        sortName: 'hits'
		       
		    }*/
			<c:if test="${fns:getUser().isShop() == false}">
			,{
		        field: 'point',
		        title: '铜板',
		        sortable: true,
		        sortName: 'point'
		       
		    }
			</c:if>
			,{
		        field: 'state',
		        title: '状态',
		        sortable: true,
		        sortName: 'state',
		        formatter:function(value, row , index){
		        	if(value == '0'){
		        		return "<font class=\"label label-success\">上架中</font>";
		        	}else if(value == '1'){
		        		return "<font class=\"label label-danger\">已下架</font>";
		        	}
		        	return "";
		        	//return jp.getDictLabel(${fns:toJson(fns:getDictList('product_state'))}, value, "-");
		        }
		       
		    }
			,{
		        field: 'oldPrice',
		        title: '市场价',
		        sortable: true,
		        sortName: 'oldPrice'
		       
		    }
			,{
		        field: 'discount',
		        title: '优惠券',
		        sortable: true,
		        sortName: 'discount'
		       
		    }
			,{
		        field: 'price',
		        title: '券后价',
		        sortable: true,
		        sortName: 'price'
		       
		    }
			,{
		        field: 'amount',
		        title: '结算价',
		        sortable: true,
		        sortName: 'amount'

    }
        , {
        field: 'isTuijian',
        title: '推荐',
        sortable: true,
        sortName: 'isTuijian',
        formatter: function (value, row, index) {
            return jp.getDictLabel(${fns:toJson(fns:getDictList('yes_no'))}, value, "-");
        }

    },
        {
            field: 'isYg',
            title: '预购',
            sortable: true,
            sortName: 'isYg',
            formatter: function (value, row, index) {
                return jp.getDictLabel(${fns:toJson(fns:getDictList('yes_no'))}, value, "-");
            }

        },
        {
            field: 'isDl',
            title: '代理',
            sortable: true,
            sortName: 'isDl',
            formatter: function (value, row, index) {
                return jp.getDictLabel(${fns:toJson(fns:getDictList('yes_no'))}, value, "-");
            }

        }
			/*,{
		        field: 'area.name',
		        title: '区县',
		        sortable: true,
		        sortName: 'area.name'
		       
		    }*/
			,{
		        field: 'auditState',
		        title: '审核状态',
		        sortable: true,
		        sortName: 'auditState',
		        formatter:function(value, row , index){
		        	if(value == '0'){
		        		return "<font class=\"label label-warning\">待审核</font>";
		        	}else if(value == '1'){
		        		return "<font class=\"label label-success\">审核通过</font>";
		        	}else if(value == '2'){
		        		return "<font class=\"label label-danger\">审核拒绝</font>";
		        	}
		        	return "";
		        	//return jp.getDictLabel(${fns:toJson(fns:getDictList('product_audit_state'))}, value, "-");
		        }
		    }
			/*,{
		        field: 'auditDate',
		        title: '审核时间',
		        sortable: true,
		        sortName: 'auditDate'
		       
		    }*/
			,{
		        field: 'updateDate',
		        title: '更新时间',
		        sortable: true,
		        sortName: 'updateDate'
		       
		    }
		    ,{
				field: 'nodelarea',
				title: '不发货区域',
				sortable: true,
				sortName: 'nodelarea'

			}
			,{
				field: 'remarks',
				title: '备注'
					
			}
			,{
		        field: '',
		        title: '操作',
		        formatter:function(value, row , index){
		        	var result = "";
					 if(row.state == '1'){
						result += "<a href='javascript:updateState(\""+row.id+"\",0)' class=\"label label-success\">上架</a>";
					}else if (row.auditState == '0') {
					   <c:if test="${fns:hasPermission('product:product:audit')}">
						   result += "<a href='javascript:audit(\""+row.id+"\",1)' class=\"label label-success\">通过</a>";
						   result += "<a href='javascript:audit(\""+row.id+"\",2)' class=\"label label-danger\">拒绝</a>";
					   </c:if>
					} else if(row.state == '0'){
						result += "<a href='javascript:updateState(\""+row.id+"\",1)' class=\"label label-danger\">下架</a>";
					}
					return result;
		        }
		       
		    }
		     ]
		
		});
		
		  
	  if(navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i)){//如果是移动端

		 
		  $('#productTable').bootstrapTable("toggleView");
		}
	  
	  $('#productTable').on('check.bs.table uncheck.bs.table load-success.bs.table ' +
                'check-all.bs.table uncheck-all.bs.table', function () {
            $('#remove').prop('disabled', ! $('#productTable').bootstrapTable('getSelections').length);
            $('#view,#edit,#skuManager').prop('disabled', $('#productTable').bootstrapTable('getSelections').length!=1);
        });
		  
		$("#btnImport").click(function(){
			jp.open({
			    type: 2,
                area: [500, 200],
                auto: true,
			    title:"导入数据",
			    content: "${ctx}/tag/importExcel" ,
			    btn: ['下载模板','确定', '关闭'],
				btn1: function(index, layero){
					  jp.downloadFile('${ctx}/product/product/import/template');
				  },
			    btn2: function(index, layero){
						var iframeWin = layero.find('iframe')[0]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
						iframeWin.contentWindow.importExcel('${ctx}/product/product/import', function (data) {
							if(data.success){
								jp.success(data.msg);
								refresh();
							}else{
								jp.error(data.msg);
							}
						   jp.close(index);
						});//调用保存事件
						return false;
				  },
				 
				  btn3: function(index){ 
					  jp.close(index);
	    	       }
			}); 
		});
	  $("#export").click(function(){//导出Excel文件
	        var searchParam = $("#searchForm").serializeJSON();
	        searchParam.pageNo = 1;
	        searchParam.pageSize = -1;
            var sortName = $('#productTable').bootstrapTable("getOptions", "none").sortName;
            var sortOrder = $('#productTable').bootstrapTable("getOptions", "none").sortOrder;
            var values = "";
            for(var key in searchParam){
                values = values + key + "=" + searchParam[key] + "&";
            }
            if(sortName != undefined && sortOrder != undefined){
                values = values + "orderBy=" + sortName + " "+sortOrder;
            }

			jp.downloadFile('${ctx}/product/product/export?'+values);
	  })
	  $("#search").click("click", function() {// 绑定查询按扭
		  $('#productTable').bootstrapTable('refresh');
		});
	 
	 $("#reset").click("click", function() {// 绑定查询按扭
		  $("#searchForm  input").val("");
		  $("#searchForm  select").val("");
		   $("#searchForm  .select-item").html("");
		  $('#productTable').bootstrapTable('refresh');
		});
	
	 $("#back").click("click", function() {// 绑定查询按扭
		  $("#right").hide();
		  $("#left").attr("class", "col-sm-12");
			setTimeout(function(){
				$("#left").fadeIn(500);
			},500);
		});
		
	});
		
  function getIdSelections() {
        return $.map($("#productTable").bootstrapTable('getSelections'), function (row) {
            return row.id
        });
    }
function getSelections() {
	return $.map($("#productTable").bootstrapTable('getSelections'), function (row) {
		return row;
	});
}
  function getStateSelections() {
	  return $.map($("#productTable").bootstrapTable('getSelections'), function (row) {
		  return row.state
	  });
  }
  
  function deleteAll(){

		jp.confirm('确认要删除该云店商品记录吗？', function(){
			jp.loading();  	
			jp.get("${ctx}/product/product/deleteAll?ids=" + getIdSelections(), function(data){
         	  		if(data.success){
         	  			$('#productTable').bootstrapTable('refresh');
         	  			jp.success(data.msg);
         	  		}else{
         	  			jp.error(data.msg);
         	  		}
         	  	})
          	   
		})
  }
  function audit(id,type){
	  var title = "";
	  if(type=='1'){
		  title="确认要通过该商品审核吗？";
	  }else{
		  title="确认要拒绝该商品审核吗？";
	  }
	  jp.confirm(title, function(){
		  if(type=='1'){
			  jp.loading();  	
			  jp.get("${ctx}/product/product/audit?id=" + id + "&type=" + type, function(data){
				  if(data.success){
					  jp.success(data.msg);
				  }else{
					  jp.error(data.msg);
				  }
				  $('#productTable').bootstrapTable('refresh');
			  })
		  } else {
			  jp.prompt("备注", function(text) {
				  jp.loading();  	
				  jp.get("${ctx}/product/product/audit?id=" + id + "&type=" + type + "&remarks=" + text, function(data){
					  if(data.success){
						  jp.success(data.msg);
					  }else{
						  jp.error(data.msg);
					  }
					  $('#productTable').bootstrapTable('refresh');
				  })
				});
		  }
	  })
  }
  function updateState(id,type){
	  var title = "";
	  if(type=='1'){
		  title="确认要下架该商品吗？";
	  }else{
		  title="确认要上架该商品吗(上架需要管理员审核)？";
	  }
	  jp.confirm(title, function(){
		  jp.loading();  	
		  jp.get("${ctx}/product/product/updateState?id=" + id + "&type=" + type, function(data){
			  if(data.success){
				  jp.success(data.msg);
			  }else{
				  jp.error(data.msg);
			  }
			  $('#productTable').bootstrapTable('refresh');
		  })
		  
	  })
  }
    //刷新列表
  function refresh() {
      $('#productTable').bootstrapTable('refresh');
  }
  function childRefresh() {
	  $('#productSkuTable').bootstrapTable('refresh');
  }
  function add(){
	  jp.openSaveDialog('新增云店商品', "${ctx}/product/product/form",'1200px', '800px');
  }
  
   function edit(id,state){//没有权限时，不显示确定按钮
       if(id == undefined){
	      id = getIdSelections();
	      state = getStateSelections();
	}
	    if(${fns:getUser().isShop()} == false){
	    	jp.openSaveDialog('编辑云店商品', "${ctx}/product/product/form?id=" + id, '1200px', '800px');
	    }else if(state == '0'){
    	   jp.openViewDialog('查看云店商品', "${ctx}/product/product/form?id=" + id + "&isread=1", '1200px', '800px');
       } else {
    	   jp.openSaveDialog('编辑云店商品', "${ctx}/product/product/form?id=" + id, '1200px', '800px');
       }
  }

  
 function view(id){//没有权限时，不显示确定按钮
      if(id == undefined){
             id = getIdSelections();
      }
      jp.openViewDialog('查看云店商品', "${ctx}/product/product/form?id=" + id + "&isread=1", '1200px', '800px');
 }
 function skuDetail(id){//没有权限时，不显示确定按钮
	 jp.openSaveDialog('查看云店商品规格', "${ctx}/product/product/skuForm?id=" + id, '1200px', '800px');
 }
  
  
  
  
		   
  function detailFormatter(index, row) {
	  var htmltpl =  $("#productChildrenTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g,"");
	  var html = Mustache.render(htmltpl, {
			idx:row.id
		});
	  $.get("${ctx}/product/product/detail?id="+row.id, function(product){
    	var productChild1RowIdx = 0, productChild1Tpl = $("#productChild1Tpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g,"");
		var data1 =  product.productSkunameList;
		for (var i=0; i<data1.length; i++){
			data1[i].dict = {};
			addRow('#productChild-'+row.id+'-1-List', productChild1RowIdx, productChild1Tpl, data1[i]);
			productChild1RowIdx = productChild1RowIdx + 1;
		}
				
      	  			
      })
     
        return html;
    }
  
	function addRow(list, idx, tpl, row){
		$(list).append(Mustache.render(tpl, {
			idx: idx, delBtn: true, row: row
		}));
	}
	
/*	$(document).ready(function() {
		var productSkuTable =	$('#productSkuTable').bootstrapTable({
				  //请求方法
	                method: 'get',
	                dataType: "json",
	                 //是否显示行间隔色
	                striped: true,
	                //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）     
	                cache: false,    
	                //是否显示分页（*）  
	                pagination: false,   
	                //这个接口需要处理bootstrap table传递的固定参数,并返回特定格式的json数据  
	                url: "${ctx}/productsku/productSku/dataByProductId",
	                //默认值为 'limit',传给服务端的参数为：limit, offset, search, sort, order Else
	                //queryParamsType:'',   
	                ////查询参数,每次调用是会带上这个参数，可自定义                         
	                queryParams : function(params) {
	                    return {'product.id':$("#productId").val()};
	                },
	                //分页方式：client客户端分页，server服务端分页（*）
	                sidePagination: "server",
	                columns: [
				    {
				    	field: 'title',
				        title: '标题'
				    },
				    {
				    	field: 'image',
				    	title: '图片',
				    	formatter:  function operateFormatter(value, row, index) {
				    		if(value != null && value != ''){
				    			return '<img   onclick="jp.showPic(\''+value+'\')"'+' height="50px" src="'+value+'">';
				    		}
				    		return "";
	        		    }
				    },
				    {
				    	field: 'oldPrice',
				        title: '市场价'
				       
				    },
				    {
				    	field: 'discount',
				    	title: '优惠券'
				    		
				    },
				    {
				    	field: 'price',
				    	title: '券后价'
				    		
				    },
				    {
				    	field: 'groupPrice',
				    	title: '拼团价'
				    		
				    },
				    {
				    	field: 'amount',
				    	title: '结算价'
				    		
				    },
				    {
				    	field: 'stock',
				        title: '库存'
				       
				    },
				    {
				    	field: 'updateDate',
				    	title: '更新时间'
				    		
				    },
				    {
	                    field: 'operate',
	                    title: '操作',
	                    align: 'center',
	                    events: {
	        		        'click .edit': function (e, value, row, index) {
	        		        	jp.openSaveDialog('编辑商品规格', '${ctx}/productsku/productSku/form?id='+row.id+'&productId=' + $("#productId").val(),'800px', '500px');
	        		        },
						    'click .del': function (e, value, row, index) {
		    		        	
		    		        	jp.confirm('确认要删除商品规格吗？',function(){
		    		        		jp.loading();
		    		        		$.get('${ctx}/productsku/productSku/delete?id='+row.id, function(data){
			                    	  		if(data.success){
			                    	  			$('#productSkuTable').bootstrapTable("refresh");
			                    	  			jp.success(data.msg);
			                    	  		}else{
			                    	  			jp.error(data.msg);
			                    	  		}
			                    	  	})
		    		        	});
		    		        }
	        		    },
	                    formatter:  function operateFormatter(value, row, index) {
	                    	var labelArray = [];
	                    	labelArray[0] = '<a href="#" class="edit" title="编辑" >[编辑] </a>';
	                    	if(${fns:getUser().isShop()} == false || row.product.state=='1'){
	                    		labelArray[1] = '<a href="#" class="del" title="删除" >[删除] </a>';
	                    	}
	                    	return labelArray.join('');
	        		        return [
	    						'<a href="#" class="edit" title="编辑" >[编辑] </a>',
	    						'<a href="#" class="del" title="删除" >[删除] </a>'
	        		        ].join('');
	        		    }
	                }]
				
				});
			
			  if(navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i)){//如果是移动端
				  $('#productSkuTable').bootstrapTable("toggleView");
				}
			  
			  $("#subsectionButton").click(function(){
					jp.openSaveDialog('新增商品规格', '${ctx}/productsku/productSku/form?productId=' + $("#productId").val(),'800px', '500px');
			  });
			  
			  });*/

	  

</script>
<script type="text/template" id="productChildrenTpl">//<!--
	<div class="tabs-container">
		<ul class="nav nav-tabs">
				<li class="active"><a data-toggle="tab" href="#tab-{{idx}}-1" aria-expanded="true">商品规格名称</a></li>
		</ul>
		<div class="tab-content">
				 <div id="tab-{{idx}}-1" class="tab-pane fade in active">
						<table class="ani table">
						<thead>
							<tr>
								<th>规格名称</th>
								<th>更新时间</th>
							</tr>
						</thead>
						<tbody id="productChild-{{idx}}-1-List">
						</tbody>
					</table>
				</div>
		</div>//-->
	</script>
	<script type="text/template" id="productChild1Tpl">//<!--
				<tr>
					<td>
						{{row.title}}
					</td>
					<td>
						{{row.updateDate}}
					</td>
				</tr>//-->
	</script>
